<template>
  <div class="base-container" id="main">
    <t-form ref="form" :data="queryParams" label-width="80" @submit="()=>{this.pagination.current=1;this.queryParams.pageNum=1;this.getList()}" @reset="()=>{this.queryParams.pageNum=1;this.queryParams.pageNum=1;this.getList()}">
      <t-row style="border-bottom: 1px solid #E5E6EB;margin-bottom: 10px">
        <t-col :span="11" class="query-form-inline">
          <t-form-item label="活动名称" name="name">
            <t-input
              v-model="queryParams.name"
              clearable
              placeholder="请输入标准名称"
              style="width: 240px"
            />
          </t-form-item>
          <t-form-item label="宣贯单位" name="unitName">
            <t-input
              v-model="queryParams.unitName"
              clearable
              placeholder="请输入标准名称"
              style="width: 240px"
            />
          </t-form-item>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button theme="primary" type="submit"> 查询</t-button>
          <t-button theme="default" variant="outline" type="reset">重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <div class="btn-group-inline">
      <t-button @click="apply" variant="outline" theme="primary">
        <t-icon name="add" slot="icon"/>
        新增
      </t-button>
    </div>
    <t-table rowKey="index" size="small" :data="data" :columns="columns" hover :pagination="pagination"
             :loading="dataLoading" :sort="sort" :hideSortTips="true" @sort-change="sortChange" multipleSort >
      <template #projectName="{ row }">
        <t-link @click="nameClick(row)" hover="color" theme="primary">{{ row.projectName }}</t-link>
      </template>
      <template #formulateType="{ row }">
        {{ row.formulateType | filterByDict(dict.type.formulate_type) }}
      </template>
      <template #reviseNum="{ row }">
        {{row.reviseNum || "-"}}
      </template>
      <template #consistencyDegree="{ row }">
        {{row.consistencyDegree || "-"}}
      </template>
      <template #completeDate="{ row }">
        {{row.completeDate || "-"}}
      </template>
      <template #internationalStandardNum="{ row }">
        {{row.internationalStandardNum || "-"}}
      </template>
      <template #manageDeptId="{ row }">
        {{ row.manageDeptId | filterByTree(deptMenuOptions) }}
      </template>
      <template #localStandardStatus="{ row }">
        <t-tag  @click="dialog.header=row.projectName;dialog.objId=row.id;dialog.open_approve_list=true" class="cursor-pointer" :theme="handleTheme(row.localStandardStatus, dict.type.local_standard_status)" variant="light">
          {{ row.localStandardStatus | filterByDict(dict.type.local_standard_status) }}
        </t-tag>
      </template>
      <template #op="{ row }">
        <t-button size="small" @click="itemInfo(row)" variant="text" class="t-button-link">
          <t-icon name="info-circle" slot="icon"/>
          详情
        </t-button>
        <t-button size="small" @click="edit(row)" variant="text" class="t-button-link">
          <t-icon name="edit-1" slot="icon"/>
          修改
        </t-button>
        <!-- <t-button @click="" size="small"
                  variant="text" class="t-button-link">
          <t-icon name="file-pdf" slot="icon"/>
          导出PDF
        </t-button> -->
        <t-button
          theme="danger"
          @click="deleteVisible=true;nowRow=row"
          size="small"
          variant="text" class="t-button-link">
          <t-icon name="delete" slot="icon"/>
          删除
        </t-button>
      </template>
    </t-table>
    <t-dialog :visible.sync="deleteVisible" @confirm="deleteById"  >
      <p>您确定要删除吗？</p>
    </t-dialog>
    <t-dialog :visible.sync="addVisible" @confirm="addPlans" confirmBtn="提交" cancelBtn="暂存" :header="header" @close="closeAdd" width="30%">
      <t-form :data="formData" :colon="true" :rules="rules" ref="form">
        <t-form-item label="标准名称" name="localId">
          <t-select  style="width: 240px" clearable filterable v-model="formData.localId"
                     :options="bzhdata">
          </t-select>
        </t-form-item>
        <t-form-item label="活动名称" name="name">
          <t-input
            v-model="formData.name"
            clearable
            placeholder="请输入计划名称"
            style="width: 240px"
          />
        </t-form-item>
        <t-form-item label="活动日期" name="activityDate">
          <t-date-picker  v-model="formData.activityDate" clearable allow-input  style="width: 240px" />
        </t-form-item>
        <t-form-item label="宣贯单位" name="unitName">
          <t-input
            v-model="formData.unitName"
            clearable
            placeholder="请输入宣贯单位"
            style="width: 240px"
          />
        </t-form-item>
        <t-form-item label="负责人" name="leaderName">
          <t-input
            v-model="formData.leaderName"
            clearable
            placeholder="请输入负责人"
            style="width: 240px"
          />
        </t-form-item>
        <t-form-item label="活动内容" name="note">
          <t-textarea  v-model="formData.note" placeholder="请输入活动内容" />
        </t-form-item>

        <t-form-item label="相关附件" name="projectFileData">
          <file-upload v-model="projectFileData.fileIds" :moduleKey="projectFileData.moduleKey"
                           :fileList="projectFileData.fileLists"
                           :multiple="true">
                <t-button variant="outline">
                  <t-icon name="cloud-upload" slot="icon"/>
                  点击上传
                </t-button>
              </file-upload>
        </t-form-item>
      </t-form>
    </t-dialog>
    <t-dialog v-if="infoVisible" :visible.sync="infoVisible"  @confirm="addPlans" :header="infoDetail.name" :confirmBtn="null">
      <t-form :data="infoDetail" :colon="true" ref="form">
<!--        <t-form-item label="标准名称" name="localStandardName">-->
<!--          {{infoDetail.localStandardName}}-->
<!--        </t-form-item>-->
        <t-form-item label="活动名称" name="name">
          {{infoDetail.name}}
        </t-form-item>
        <t-form-item label="活动日期" name="activityDate">
          {{infoDetail.activityDate}}
        </t-form-item>
        <t-form-item label="宣贯单位" name="unitName">
          {{infoDetail.unitName}}
        </t-form-item>
        <t-form-item label="负责人" name="leaderName">
          {{infoDetail.leaderName}}
        </t-form-item>
        <t-form-item label="活动内容" name="note">
          {{infoDetail.note}}
        </t-form-item>
        <t-form-item label="相关附件" name="files">
          <div style="display: flex; flex-direction: column;">
            <t-link v-for="link in infoDetail.files" :key="link.id" hover="color" :href="link.url">{{ link.name }}</t-link>
          </div>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload/index.vue"
import {getFiles} from "@/api/common";

export default {
  name: "iso-activities-my",
  dicts:["formulate_type","bzh_approve_type","approve_status","local_standard_status"],
  components: {
    FileUpload
  },
  data() {
    return {
      header:"新增贯标活动",
      infoVisible:false,
      projectFileData: {
        id: 1,
        c1: "其他",
        c2: "否",
        fileIds: [],
        fileLists: [],
        moduleKey: "projectBSOther",
        require: false
      },
      rules: {
        localId: [
          {
            required: true,
            message: "标准不能为空",
          },
        ],
        name: [
          {
            required: true,
            message: "活动名称不能为空",
          },
        ],
        activityDate: [
          {
            required: true,
            message: "活动日期不能为空",
          },
        ],
        unitName: [
          {
            required: true,
            message: "宣贯单位不能为空",
          },
        ],
        leaderName: [
          {
            required: true,
            message: "负责人不能为空",
          },
        ],
        note: [
          { required: true, message: "计划内容不能为空"}
        ],
      },
      formData:{
        localId:[],
        name:"",
        activityDate:"",
        unitName:'',
        leaderName:"",
        note:""
      },
      addVisible:false,
      nowRow:"",
      deleteVisible:false,
      deptMenuOptions:[],
      dialog: {
        open: false,
        header: "",
        row: {},
        data: {},
        open_project_detail: false,
        open_outline_detail: false,
        open_contract_detail: false,
        objId: 0,
        open_approve_list: false
      },
      detailDialog:{
        id:"",
        header:"",
        visible: false,
      },
      queryParams:{
        pageNum:1,
        pageSize:10,
        name:"",
        unitName:"",
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showPageSize: true,
        pageSizeOptions: [10, 20, 30, 50],
        showFirstAndLastPageBtn: false,
        onChange: (pageInfo) => {
          Object.assign(this.pagination,pageInfo)
          this.queryParams.pageNum = pageInfo.current || 1;
          this.queryParams.pageSize = pageInfo.pageSize;
          this.getList()
        },
      },
      sort:[],
      bzhdata:[],
      dataLoading: false,
      columns:[
        {
          colKey: "standardName",
          title: "标准名称",
          align: "center",
          width: 160,
        },
        {
          colKey: "name",
          title: "活动名称",
          align: "center",
          width: 160,
        },
        {
          colKey: "activityDate",
          title: "活动日期",
          align: "center",
          width: 160,
        },
        {
          colKey: "leaderName",
          title: "负责人",
          align: "center",
          width: 160,
        },
        {
          colKey: "note",
          title: "计划内容",
          align: "center",
          width: 160,
        },
        // {
        //   colKey: "declareDeptName",
        //   title: "申报单位名称",
        //   align: "center",
        //   width: 160,
        // },

        {
          colKey: "op",
          title: "操作",
          align: "center",
          width: 240,
          fixed: 'right'
        },
      ],
      opinionVisible: true,
      data: [],
      infoDetail:{},
    }
  },
  async created() {
    await this.getDeptTreeSelect()
    await this.getBzhList()
    this.getList()
  },
  methods: {
    closeAdd(){
      this.$refs.form.reset()
      this.addVisible = false
    },
    edit(row){
      this.$api.bzh.iso.detailAct(row.id).then(response=>{
        this.formData = response.data
        this.header = "修改贯标活动"
        getFiles(response.data.id).then((res) => {
          const files = []
          res.data.forEach((item) => {
            files.push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.projectFileData.fileLists = files || [];
          this.projectFileData.fileIds = files?.map(val => val.id) || [];
        }).catch((e) => {
          this.$message.error(e.toString());
        });
        this.addVisible = true
      }).catch(e=>{
        this.$message.error(e.toString())
      })

    },
    getBzhList(){
      const tempParams = {}
      Object.assign(tempParams, this.queryParams)
      tempParams.pageSize = 1000
      tempParams.standardStatusList = ['44', '46']
      this.$api.bzh.standard.myList(tempParams).then(response=>{
        response.rows.forEach(item=>{
          const obj = {
            label:item.projectName,
            value:item.id
          }
          this.bzhdata.push(obj)
        })
      }).catch(e=>{
        this.$message.error(e.toString())
      })
    },
    addPlans(){
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const sysAttMainIds = []
          sysAttMainIds.push(...this.projectFileData.fileIds)
          // this.formData.localId = this.nowRow.id
          if(this.header === "修改贯标活动"){
            this.$api.bzh.iso.updateAct({
              ...this.formData,
              sysAttMainVo: {
                sysAttMainIds
              }
            }).then(res=>{
              this.$message.success("修改成功")
              this.$refs.form.reset()
              this.getList()
              // this.$refs.form.reset()
              this.addVisible = false
            }).catch(err=>{
              this.$message.error(err.toString())
              // this.$refs.form.reset()
              // this.addVisible = false
            })
          }else{
            delete this.formData.id
            this.$api.bzh.iso.addAct({
              ...this.formData,
              sysAttMainVo: {
                sysAttMainIds
              }
            }).then(res=>{
              this.$refs.form.reset()
              this.$message.success("新增成功")
              // this.$refs.form.reset()
              this.getList()
              // this.$refs.form.reset()
              this.addVisible = false
            }).catch(err=>{
              this.$message.error(err.toString())
              // this.$refs.form.reset()
              // this.addVisible = false
            })
          }
        }else{
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    // 删除按钮
    deleteById(){
      this.$api.bzh.iso.deleteAct(this.nowRow.id).then(response=>{
        this.getList()
        this.$message.success("删除成功")
        this.deleteVisible = false
      }).catch(error=>{
        this.$message.error(error.toString())
      })
    },
    itemInfo(row){
      this.infoVisible = true
      this.$api.bzh.iso.detailAct(row.id).then(response=> {
        this.infoDetail =response.data
        getFiles(row.id).then((res) => {
          const files = []
          res.data.forEach((item) => {
            files.push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.infoDetail = {
            ...response.data,
            files
          }
          // this.projectFileData.forEach((val,index)=>{
          //   this.projectFileData[index].fileLists = files[val.moduleKey] || [];
          //   this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
          // })
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      })

    },
    apply(){
      this.header = "新增贯标活动"
      // this.$refs.form.reset()
      this.addVisible = true
      // this.$router.push(`/bzh/iso/iso-act-apply`);
    },
    getDeptTreeSelect(){
      return this.$api.system.dept.treeSelectAllIn().then(response=>{
        this.deptMenuOptions = response.data
      }).catch(e=>{
        this.$message.error(e.toString())
      })
    },
    // 点击列表名字事件
    nameClick(row){
      this.detailDialog.id = row.id
      this.detailDialog.header = row.projectName
      this.detailDialog.visible = true
    },
    // 关闭详情弹框
    closeBzhDialog(data){
      this.detailDialog.visible = data
    },
    sortChange(sort){
      this.sort = sort;
      let orderByColumn = []
      let isAsc = []
      if(sort instanceof Array){
        orderByColumn = sort.map(val=>val.sortBy)
        isAsc = sort.map(val=>val.descending?`desc`:`asc`)
      }else {
        orderByColumn = [sort.sortBy]
        isAsc = [sort.descending?`desc`:`asc`]
      }
      this.queryParams.orderByColumn = orderByColumn.join(",")
      this.queryParams.isAsc = isAsc.join(",")
      this.getList();
    },
    getList(){
      this.dataLoading = true
      this.$api.bzh.iso.actMyList(this.queryParams).then(response=>{
        this.pagination.total = response.total
        this.data = response.rows
        this.dataLoading = false
      }).catch(e=>{
        this.dataLoading = false
        this.$message.error(e.toString())
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>

